package com.cb.controller.admin.order;

import java.io.IOException;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ui.ModelMap;
import org.springframework.web.servlet.ModelAndView;

import webservices.mobile.MoblieUtil;

import com.cb.common.enumType.OrderStatus;
import com.cb.common.map.BOrderCommon;
import com.cb.common.util.ConfigUtil;
import com.cb.common.webapp.context.RequestContext;
import com.cb.core.command.QueryFilter;
import com.cb.core.command.QueryResult;
import com.cb.core.controller.BaseListController;
import com.cb.core.util.DateUtil;
import com.cb.domain.model.order.BOrder;
import com.cb.domain.model.order.Flight;
import com.cb.domain.model.order.OrderLog;
import com.cb.domain.model.order.Passenger;
import com.cb.domain.model.order.PassengerDto;
import com.cb.domain.model.system.SystemUser;
import com.cb.domain.service.order.BOrderManager;
import com.cb.domain.service.order.OrderLogManager;
import com.cb.domain.service.order.PassengerManager;

/**
 * 
 * @Author author
 * @Vesion 1.0 Create Time:
 *         <p>
 *         <b>Class Description:</b>[TODO]
 *         <p>
 */
public class BOrderController extends BaseListController {

	@Autowired
	private BOrderManager bOrderManager;
	@Autowired
	private PassengerManager passengerManager;
	@Autowired
	private OrderLogManager orderLogManager;

	/**
	 * 对象列表页，提供最基本的分页显示
	 * 
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	public ModelAndView defaultAction(HttpServletRequest request,
			HttpServletResponse response) throws Exception {

		String status = request.getParameter("orderStatus");
		QueryFilter queryFilter = new QueryFilter(request);
		if(StringUtils.isNotBlank(status)){
			queryFilter.addFilter("Q_status_L_EQ", status);
		}

		queryFilter.addSorted("createTime", QueryFilter.SORT_DESC);
		QueryResult bOrders = bOrderManager.getAll(queryFilter);

		return new ModelAndView("admin/order/bOrderList", "bOrders", bOrders);
	}

	/**
	 * 拆分订单页面
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	public ModelAndView splitOrder(HttpServletRequest request,
			HttpServletResponse response) throws Exception {

		String orderId = request.getParameter("orderId");

		BOrder bOrders = bOrderManager.get(Long.valueOf(orderId));

		return new ModelAndView("admin/order/splitOrder", "passengers", bOrders.getPassengers()).addObject("orderId", orderId);
	}
	
	/**
	 * 拆分订单
	 * @param request
	 * @param response
	 * @throws Exception
	 */
	public void doSplitOrder(HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		String message="false";
		String passengerIds = request.getParameter("passengerIds");
		String orderId = request.getParameter("orderId");
		if(StringUtils.isNotBlank(passengerIds) && StringUtils.isNotBlank(orderId)){
			BOrder bOrder=bOrderManager.get(Long.valueOf(orderId));
			String passengerId []= passengerIds.substring(0, passengerIds.lastIndexOf(",")).split(",");
			Boolean isSpilt=bOrderManager.newSplitBOrder(bOrder, passengerId, bOrder.getStatus());
			if (isSpilt) {
				message="true";
			}
		}
		response.getWriter().write(message);
	}
	
	/**
	 * UPDATE状态
	 * 
	 * @param request
	 * @param response
	 * @return
	 */
	public ModelAndView updateStatus(HttpServletRequest request,
			HttpServletResponse response) {
		String orderId = request.getParameter("id");
		String status = request.getParameter("status");
		if (StringUtils.isNotEmpty(orderId) && StringUtils.isNotEmpty(status)) {
			BOrder order = bOrderManager.get(new Long(orderId));
			if (null != order) {
				order.setStatus(new Long(status));
				bOrderManager.save(order);
			}
		}

		return new ModelAndView(getSuccessView());
	}

	/**
	 * UPDATE订单类型
	 * 
	 * @param request
	 * @param response
	 * @return
	 */
	public ModelAndView updateOrderType(HttpServletRequest request,
			HttpServletResponse response) {
		String orderId = request.getParameter("id");
		String status = request.getParameter("type");
		if (StringUtils.isNotEmpty(orderId) && StringUtils.isNotEmpty(status)) {
			BOrder order = bOrderManager.get(new Long(orderId));
			if (null != order) {
				order.setStatus(new Long(status));
				Long orderType = order.getOrderType();
				String actionStr = "更新订单类型";
				for (OrderStatus temp : BOrderCommon.getOrderStatusMap()
						.keySet()) {
					Long obj = BOrderCommon.getOrderStatusMap().get(temp);
					if (orderType == obj) {
						String oldText=getText("bOrder.status"+status);
						String newText=getText("bOrder.status"+obj.toString());
						actionStr+=oldText+"为"+newText;
					}
				}
				orderLogManager.saveLog(actionStr, "2", orderId);
				bOrderManager.save(order);
			}
		}

		return new ModelAndView(getSuccessView());
	}

	/**
	 * 拆分订单
	 * 
	 * @param request
	 * @param response
	 * @return
	 */
	public ModelAndView splitOrderObj(HttpServletRequest request,
			HttpServletResponse response) {
		String orderId = request.getParameter("id");
		if (StringUtils.isNotEmpty(orderId)) {
			BOrder order = bOrderManager.get(new Long(orderId));
			if (null != order) {
				String res = bOrderManager.splitBOrder(order);
				saveMessage(request, res);
			}
		}
		return new ModelAndView(getSuccessView());
	}
	
	/**
	 * 新拆分订单
	 * @param request
	 * @param response
	 * @return
	 */
	/*public ModelAndView newSplitOrderObj(HttpServletRequest request,
			HttpServletResponse response) {
		String orderId = request.getParameter("orderId");
		String []passengerIds = request.getParameterValues("passengerIds");
		if (StringUtils.isNotEmpty(orderId)) {
			BOrder order = bOrderManager.get(new Long(orderId));
			BOrder moveOrder = order;
			if (null != order) {
				List<Passenger> newPas=new ArrayList<Passenger>();
				List<Passenger> movePas=new ArrayList<Passenger>();
				Set<Passenger> passengers= order.getPassengers();
				for (Iterator iterator = passengers.iterator(); iterator.hasNext();) {
					Passenger passenger = (Passenger) iterator.next();
					for (int i = 0; i < passengerIds.length; i++) {
						if(passenger.getId()==Long.valueOf(passengerIds[i])){
							newPas.add(passenger);
							order.setAllPrice((long) (order.getAllPrice()-passenger.getTotalPrice()));
						}else{
							movePas.add(passenger);
							moveOrder.setAllPrice((long) (order.getAllPrice()-passenger.getTotalPrice()));
						}
					}
				}
				bOrderManager.newSplitBOrder(order, newPas);
				bOrderManager.newSplitBOrder(moveOrder, movePas);
			}
		}
		return new ModelAndView(getSuccessView());
	}*/

	/**
	 * 批量删除，通过页面传回对象的主键数组进行逐条删除
	 * 
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	public ModelAndView multiDelete(HttpServletRequest request,
			HttpServletResponse response) {
		String[] ids = request.getParameterValues("id");
		if (ids != null) {
			for (String id : ids) {
				bOrderManager.remove(new Long(id));
			}
			saveMessage(request, getText("bOrder.mutiDeleted"));
		}
		String url = request.getHeader("Referer");
		if (StringUtils.isNotEmpty(url)) {
			return new ModelAndView("redirect:" + url);
		}
		return new ModelAndView(getSuccessView());
	}

	/**
	 * 删除单个实体对象
	 * 
	 * @param request
	 * @param response
	 * @return
	 */
	public ModelAndView delete(HttpServletRequest request,
			HttpServletResponse response) {
		String id = request.getParameter("id");
		if (StringUtils.isNotEmpty(id)) {
			BOrder bOrder = bOrderManager.get(new Long(id));
			bOrderManager.remove(bOrder);
			saveMessage(request,
					getText("bOrder.deleted", new Object[] { bOrder.getId() }));
		}
		String url = request.getHeader("Referer");
		if (StringUtils.isNotEmpty(url)) {
			return new ModelAndView("redirect:" + url);
		}
		return new ModelAndView(getSuccessView());
	}

	/**
	 * 查看实体对象详细信息
	 * 
	 * @param request
	 * @param response
	 * @return
	 */
	public ModelAndView viewDetail(HttpServletRequest request,
			HttpServletResponse response) {
		String id = request.getParameter("id");
		BOrder bOrder = null;
		if (StringUtils.isNotEmpty(id)) {
			bOrder = bOrderManager.get(new Long(id));
		}
		orderLogManager.saveLog("打开订单"+bOrder.getOrderNo(), "2",bOrder.getId().toString());
		
		QueryFilter filter=new QueryFilter();
		filter.addFilter("Q_orderId_S_EQ", bOrder.getId().toString());
		List<OrderLog> orderLogs= orderLogManager.getAllList(filter);
		
		List<PassengerDto> dtos= bOrderManager.passenger2dto(bOrder.getPassengers());
		
		ModelMap map=new ModelMap();
		map.addAttribute("bOrder", bOrder);
		map.addAttribute("orderLogs", orderLogs);
		map.addAttribute("passengerDtos", dtos);
		
		return new ModelAndView("admin/order/bOrderDetail").addAllObjects(map);
	}

	/**
	 * 退票页面
	 * 
	 * @param request
	 * @param response
	 * @return
	 */
	public ModelAndView changeReturn(HttpServletRequest request,
			HttpServletResponse response) {
		String id = request.getParameter("id");
		BOrder bOrder = null;
		if (StringUtils.isNotEmpty(id)) {
			bOrder = bOrderManager.get(new Long(id));
		}
		orderLogManager.saveLog("打开订单"+bOrder.getOrderNo(), "2",bOrder.getId().toString());
		
		QueryFilter filter=new QueryFilter();
		filter.addFilter("Q_orderId_S_EQ", bOrder.getId().toString());
		List<OrderLog> orderLogs= orderLogManager.getAllList(filter);
		
		List<PassengerDto> dtos= bOrderManager.passenger2dto(bOrder.getPassengers());
		
		ModelMap map=new ModelMap();
		map.addAttribute("bOrder", bOrder);
		map.addAttribute("orderLogs", orderLogs);
		map.addAttribute("passengerDtos", dtos);
		
		return new ModelAndView("admin/order/bOrderReturn").addAllObjects(map);
	}
	
	
	/**
	 * 查看实体对象详细信息
	 * 
	 * @param request
	 * @param response
	 * @return
	 */
	public ModelAndView updateBorder(HttpServletRequest request,
			HttpServletResponse response) {
		String id = request.getParameter("id");
		BOrder bOrder = null;
		if (StringUtils.isNotEmpty(id)) {
			bOrder = bOrderManager.get(new Long(id));
		}
		orderLogManager.saveLog("打开订单"+bOrder.getOrderNo(), "2",bOrder.getId().toString());
		
		QueryFilter filter=new QueryFilter();
		filter.addFilter("Q_orderId_S_EQ", bOrder.getId().toString());
		List<OrderLog> orderLogs= orderLogManager.getAllList(filter);
		
		
		
		List<PassengerDto> dtos= bOrderManager.passenger2dto(bOrder.getPassengers());
		
		ModelMap map=new ModelMap();
		map.addAttribute("bOrder", bOrder);
		map.addAttribute("orderLogs", orderLogs);
		map.addAttribute("passengerDtos", dtos);
		
		return new ModelAndView("admin/order/bOrderUpdate").addAllObjects(map);
		
	}

	public ModelAndView doUpdateBorder(HttpServletRequest request,
			HttpServletResponse response) {
		String id = request.getParameter("id");

		String orderStatus = request.getParameter("orderStatus");
		String pnr = request.getParameter("pnr");
		String ticketMode = request.getParameter("ticketMode");
		String price = request.getParameter("price");
		String noPay = request.getParameter("noPay");
		String ticketChannel = request.getParameter("ticketChannel");
		
		     
//		String expType = request.getParameter("expType");
		String company = request.getParameter("company");
		String orderNumber = request.getParameter("orderNumber");
		String sendtime = request.getParameter("sendtime");
		String sjr = request.getParameter("sjr");
		String contactTel = request.getParameter("contactTel");
		String address = request.getParameter("address");
		
		BOrder bOrder = null;
		if (StringUtils.isNotEmpty(id)) {
			bOrder = bOrderManager.get(new Long(id));
			
			Set<Passenger> passengers=bOrder.getPassengers();
			for (Passenger passenger : passengers) {
				String eticketNum=request.getParameter("eticketNum"+passenger.getId());
				String passengerName=request.getParameter("passengerName"+passenger.getId());
				String cardNum=request.getParameter("cardNum"+passenger.getId());
				passenger.setName(passengerName);
				passenger.setCardNum(cardNum);
				passenger.setEticketNum(eticketNum);
			}
			
			Set<Flight> flights=bOrder.getFlights();
			Map map=request.getParameterMap();
			for (Flight flight : flights) {
				String flightCode=request.getParameter("flightCode"+flight.getId());
				String c_deptDay=request.getParameter("c_deptDay"+flight.getId());
				String c_startDay=request.getParameter("c_startDay");
				String c_arriDay=request.getParameter("c_arriDay");
				if(StringUtils.isNotBlank(flightCode)){
					flight.setCode(flightCode);
				}if(StringUtils.isNotBlank(c_deptDay)){
						flight.setDepDay(c_deptDay);
						flight.setArrDay(c_deptDay);
				}if(StringUtils.isNotBlank(c_startDay)){
							flight.setDepTime(c_startDay);
				}if(StringUtils.isNotBlank(c_arriDay)){
						flight.setArrTime(c_arriDay);
				}
			}
			
//			bOrder.setExpType(Long.valueOf(expType));
			bOrder.setCompany(company);
			bOrder.setOrderNumber(orderNumber);
			if(StringUtils.isNotBlank(sendtime)){
				try {
					bOrder.setSendtime(DateUtil.convertStringToDate(sendtime));
				} catch (ParseException e) {
					// TODO Auto-generated catch block
					logger.error(e);
				}
			}
			
			bOrder.setSjr(sjr);
			bOrder.setContactTel(contactTel);
			bOrder.setAddress(address);
			
			if (StringUtils.isNotBlank(orderStatus)) {
				bOrder.setStatus(Long.valueOf(orderStatus));
			}
			if (StringUtils.isNotBlank(pnr)) {
				bOrder.setPnr(pnr);
			}
			if (StringUtils.isNotBlank(ticketMode)) {
				bOrder.setTicketMode(ticketMode);
			}
			if (StringUtils.isNotBlank(price)) {
				bOrder.setAllPrice(Long.valueOf(price));
			}
			if (StringUtils.isNotBlank(noPay)) {

				bOrder.setNoPay(Long.valueOf(noPay));
			}if (StringUtils.isNotBlank(ticketChannel)) {
				bOrder.setTicketChannel(ticketChannel);
			}
				
			String action=getText("bOrder.status"+orderStatus);
			orderLogManager.saveLog("更新订单状态为"+action, "2",bOrder.getId().toString());
			
			Boolean flag=true;
			if(bOrder.getStatus()==31){
			
			String user = ConfigUtil.getInstance().getProperty("abe.userId");
			String password = ConfigUtil.getInstance().getProperty("abe.password");
			String server = ConfigUtil.getInstance().getProperty("abe.server");
			String port = ConfigUtil.getInstance().getProperty("abe.port");
			String maxPage = ConfigUtil.getInstance().getProperty("abe.maxPage");

			String identity = getText("abe.identity", new Object[] { user,
					password, server, port, maxPage });

			flag=bOrderManager.xePnr(bOrder.getPnr(), identity);
			if(StringUtils.isNotBlank(bOrder.getCpnr())){
				flag=bOrderManager.xePnr(bOrder.getCpnr(), identity);
			}
			}
			
			if(flag){
				bOrderManager.save(bOrder);
			}
			
			if(bOrder.getStatus()==2){
				String passengerName="";
				for (Passenger passenger :passengers) {
					passengerName+=passenger.getName()+"票号"+passenger.getEticketNum()+",";
				}
				passengerName=passengerName.substring(0, passengerName.lastIndexOf(","));
				String message="";
				for (Flight flight : flights) {
					message = getText("ticket.success", new Object[] { flight.getDepDay(),
							flight.getBoardPointName(), flight.getOffPointName(), flight.getCode(),flight.getDepTime(),flight.getArrTime(),passengerName});
					break;
				}
				
				MoblieUtil.sendSms(bOrder.getContactMob(), message);
				Map<String, Object> model=new HashMap<String, Object>();
				model.put("message", message);
				if(StringUtils.isNotBlank(bOrder.getContactEmail())){
				mailEngine.sendTemplateMail("successTicket.vm", model, "订单出票成功", null, 
						new String[]{bOrder.getContactEmail()}, null, null, null, null, true);
				}
			 }
			
		}
		return new ModelAndView("redirect:/admin/order/bOrders.do?cmd=updateBorder&id="+bOrder.getId());
	}

	/**
	 * 获取所有类型订单数量
	 * 
	 * @param request
	 * @param response
	 * @return
	 * @throws IOException 
	 */
	public void getOrderCounts(HttpServletRequest request,
			HttpServletResponse response) throws IOException {
		
		String countStr = "";
		Map<OrderStatus, Long> orderStatusMap = BOrderCommon.getOrderStatusMap();
//		Map<String, String> outputMap = new HashMap<String, String>();
		
		List<String> strings=new ArrayList<String>();
		OrderStatus [] orderStatus=new OrderStatus[]{OrderStatus.WAIT_SEAT_CONFIRM,
				OrderStatus.BOOK_OK,
				OrderStatus.CANCEL_OK,
				OrderStatus.PAY_OK,
				OrderStatus.APPLY_CHANGE,
				OrderStatus.APPLY_REFUNDMENT,
				OrderStatus.WAIT_REFUNDMENT,
				};
		
		
		for (OrderStatus orderStatu : orderStatus) {
			Long type = orderStatusMap.get(orderStatu);
			Integer typeCount = bOrderManager.getOrderCountByType(type.toString());
			strings.add(typeCount.toString());
//			outputMap.put(orderStatu.toString(), typeCount.toString());
		}
	
		for (String string : strings) {
			countStr+=string+";";
		}
		
	/*	if (outputMap.size() > 0) {
			for (String key : outputMap.keySet()) {
				String value = outputMap.get(key);
				countStr += key + ":" + value + ";";
			}
		}*/
			response.getWriter().print(countStr);
	}

	/**
	 * 退票页面
	 * @param request
	 * @param response
	 * @return
	 */
	public ModelAndView goReturn(HttpServletRequest request,
			HttpServletResponse response) {

		String id = request.getParameter("id");
		BOrder bOrder = null;
		if (StringUtils.isNotEmpty(id)) {
			bOrder = bOrderManager.get(new Long(id));
		}
		orderLogManager.saveLog("打开订单", "2",bOrder.getId().toString());
		return new ModelAndView("admin/order/backMoney", "bOrder", bOrder);
	}

	/**
	 * 退票操作
	 * @param request
	 * @param response
	 * @return
	 */
	public ModelAndView postReturn(HttpServletRequest request,
			HttpServletResponse response) {

		String id = request.getParameter("orderId");
		BOrder bOrder = null;
		if (StringUtils.isNotEmpty(id)) {
			bOrder = bOrderManager.get(new Long(id));
		bOrder.setStatus(BOrderCommon.getOrderStatusMap().get(
				OrderStatus.WAIT_REFUNDMENT));
		String remark = request.getParameter("remark");
		bOrder.setRemark(remark);
		bOrderManager.save(bOrder);
		orderLogManager.saveLog("更新订单为退票完成", "2",bOrder.getId().toString());
		}
		return new ModelAndView("redirect:/admin/order/bOrders.do");
	}
	
	
	public ModelAndView returnMoney(HttpServletRequest request,
			HttpServletResponse response) {
		String id = request.getParameter("id");
		BOrder bOrder = null;
		if (StringUtils.isNotEmpty(id)) {
			bOrder = bOrderManager.get(new Long(id));
			String backMoney = request.getParameter("backMoney");
			String fee = request.getParameter("fee");
			String returnType = request.getParameter("returnType");
			if (StringUtils.isNotEmpty(backMoney)) {
				bOrder.setPrice(Long.parseLong(backMoney));
			}

			if (StringUtils.isNotEmpty(fee)) {
				bOrder.setRefundFee(Double.valueOf(fee));
			}
			
			if (StringUtils.isNotEmpty(returnType)) {
				bOrder.setReturnType(Integer.valueOf(returnType));
			}

			String remark = request.getParameter("remark");
			bOrder.setRemark(remark);
			bOrder.setStatus(BOrderCommon.getOrderStatusMap().get(
					OrderStatus.REFUND_OK));
			orderLogManager.saveLog("更新订单为退款完成", "2",bOrder.getId().toString());
			bOrderManager.save(bOrder);
			
			String message = getText("returnMoney.success", new Object[] {bOrder.getOrderNo()});
			MoblieUtil.sendSms(bOrder.getContactMob(), message);
			Map<String, Object> model=new HashMap<String, Object>();
			model.put("message", message);
			if(StringUtils.isNotBlank(bOrder.getContactEmail())){
			mailEngine.sendTemplateMail("returnMoney.vm", model, "订单退款成功", null, 
					new String[]{bOrder.getContactEmail()}, null, null, null, null, true);
			}
		}
		return new ModelAndView(getSuccessView());
	}
}
